package sing.core.weight

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnFocusChangeListener
import android.widget.EditText
import android.widget.LinearLayout
import sing.core.R

class VerificationCodeView(mContext: Context, attrs: AttributeSet?) : LinearLayout(mContext, attrs), TextWatcher, View.OnKeyListener, OnFocusChangeListener {
    var et1: EditText
    var et2: EditText
    var et3: EditText
    var et4: EditText
    var list: MutableList<EditText> = arrayListOf()

    init {
        LayoutInflater.from(context).inflate(R.layout.layout_verification_code_view, this, true)

        et1 = findViewById(R.id.et_1)
        et2 = findViewById(R.id.et_2)
        et3 = findViewById(R.id.et_3)
        et4 = findViewById(R.id.et_4)

        list.add(et1)
        list.add(et2)
        list.add(et3)
        list.add(et4)

        val count = list.size
        for (i in 0 until count) {
            list[i].addTextChangedListener(this)
            list[i].setOnKeyListener(this)
            list[i].onFocusChangeListener = this
        }
    }

    var onCodeFinishListener: OnCodeFinishListener? = null

    /// 输入框数量
    var mEtNumber = 4

    var oldCount = 0
    override fun onFocusChange(view: View, b: Boolean) {
        if (b) {
            focus()
        }
    }

    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
    override fun afterTextChanged(s: Editable) {
        try {
            val str = s.toString()
            if (list[0].text != null && list[0].text!!.isNotEmpty() && str.length > 1) { // 超过2位数，可能是粘贴的
                for (index in str.indices) {
                    if (list.size > index) {
                        list[index].setText(str.substring(index, index + 1))
                    }
                }
            }
        } catch (e: Exception) {
        }

        oldCount = result.length
        if (s.isNotEmpty()) {
            focus()
        }
        if (onCodeFinishListener != null) {
            onCodeFinishListener!!.onTextChange(this, result)
            //如果最后一个输入框有字符，则返回结果
            val lastEditText = list[mEtNumber - 1]
            if ("${lastEditText.text}".length > 0 && result.length == 4) {
                onCodeFinishListener!!.onComplete(this, result)
            }
        }
    }

    override fun onKey(v: View, keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_DEL && event.action == KeyEvent.ACTION_DOWN) {
            backFocus()
        }
        return false
    }

    override fun setEnabled(enabled: Boolean) {
        val childCount = list.size
        for (i in 0 until childCount) {
            val child = list[i]
            child.isEnabled = enabled
        }
    }

    /**
     * 获取焦点
     */
    fun focus() {
        val count = list.size
        var editText: EditText
        //利用for循环找出还最前面那个还没被输入字符的EditText，并把焦点移交给它。
        for (i in 0 until count) {
            editText = list[i]
            if ("${editText.text}".length < 1 || i == 3) {
                editText.isCursorVisible = true
                editText.requestFocus()
                return
            } else {
                editText.isCursorVisible = false
                if (i == count - 1) {
                    editText.requestFocus()
                }
            }
        }
    }

    private fun backFocus() {
        val count = list.size
        var editText: EditText
        //利用for循环找出还最前面那个还没被输入字符的EditText，并把焦点移交给它。
        for (i in count - 1 downTo 0) {
            editText = list[i]
            if ("${editText.text}".isNotEmpty()) {
                editText.setText("")
                editText.isCursorVisible = true
                editText.requestFocus()
                return
            }
        }
    }

    private val result: String
        get() {
            val stringBuffer = StringBuilder()
            stringBuffer.append(et1.text)
            stringBuffer.append(et2.text)
            stringBuffer.append(et3.text)
            stringBuffer.append(et4.text)
            return stringBuffer.toString()
        }

    interface OnCodeFinishListener {
        // 文本改变
        fun onTextChange(view: View?, content: String?)

        // 输入完成
        fun onComplete(view: View?, content: String)
    }

    /**
     * 清空验证码输入框
     */
    fun setEmpty() {
        oldCount = 0
        et1.setText("")
        et2.setText("")
        et3.setText("")
        et4.setText("")
        et1.isCursorVisible = true
        et1.requestFocus()
    }

    fun getFirstEd(): EditText {
        return list[0]
    }
}

